document.addEventListener('DOMContentLoaded', function() {
    // 获取DOM元素
    const imageUpload = document.getElementById('image-file');
    const imagePreview = document.querySelector('.image-preview');
    const previewImg = document.getElementById('preview');
    const analyzeBtn = document.querySelector('.analyze-btn');
    const analysisResult = document.querySelector('.analysis-result');
    const resultCards = document.querySelector('.result-cards');
    
    let imageBlob;
    
    // 后端API地址
    const API_BASE_URL = 'http://81.69.225.207:5003/api';

    // 文件上传处理
    imageUpload.addEventListener('change', function(e) {
        const file = e.target.files[0];
        if (file) {
            if (!file.type.startsWith('image/')) {
                alert('请上传图片文件');
                return;
            }

            imageBlob = file;
            const imageUrl = URL.createObjectURL(file);
            previewImg.src = imageUrl;
            imagePreview.style.display = 'block';
            analyzeBtn.disabled = false;
        }
    });

    // 拖拽上传处理
    const dropZone = document.querySelector('.image-upload');
    
    dropZone.addEventListener('dragover', (e) => {
        e.preventDefault();
        dropZone.style.borderColor = '#2c5cff';
        dropZone.style.background = 'rgba(44, 92, 255, 0.05)';
    });

    dropZone.addEventListener('dragleave', () => {
        dropZone.style.borderColor = '#ddd';
        dropZone.style.background = 'none';
    });

    dropZone.addEventListener('drop', (e) => {
        e.preventDefault();
        dropZone.style.borderColor = '#ddd';
        dropZone.style.background = 'none';
        
        const file = e.dataTransfer.files[0];
        if (file) {
            if (!file.type.startsWith('image/')) {
                alert('请上传图片文件');
                return;
            }

            imageUpload.files = e.dataTransfer.files;
            imageBlob = file;
            const imageUrl = URL.createObjectURL(file);
            previewImg.src = imageUrl;
            imagePreview.style.display = 'block';
            analyzeBtn.disabled = false;
        }
    });

    // 图像分析按钮点击事件
    analyzeBtn.addEventListener('click', async function() {
        try {
            analyzeBtn.disabled = true;
            analyzeBtn.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 检索中...';
            analysisResult.style.display = 'block';

            // 将图片转换为Base64
            const reader = new FileReader();
            reader.readAsDataURL(imageBlob);
            
            reader.onload = async function() {
                try {
                    // 获取Base64编码（去掉前缀）
                    const base64Image = reader.result.split(',')[1];
                    
                    // 提交图像分析请求
                    const response = await fetch(`${API_BASE_URL}/image-understanding/submit`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            image: base64Image
                        })
                    });

                    if (!response.ok) {
                        throw new Error(`提交请求失败: ${response.status}`);
                    }

                    const result = await response.json();
                    
                    if (result.error) {
                        throw new Error(result.error);
                    }

                    // 创建分析结果卡片
                    const resultCard = document.createElement('div');
                    resultCard.className = 'recognition-card';
                    
                    // 格式化结果文本
                    let resultText = result.result;
                    if (typeof resultText === 'object') {
                        resultText = JSON.stringify(resultText, null, 2);
                    }
                    
                    // 根据状态显示不同的图标和颜色
                    let statusIcon = 'fa-brain';
                    let statusColor = '#2c5cff';
                    let statusText = '检索完成';
                    
                    if (result.status === 'FAILED') {
                        statusIcon = 'fa-exclamation-circle';
                        statusColor = '#dc3545';
                        statusText = '检索失败';
                    } else if (result.status === 'TIMEOUT') {
                        statusIcon = 'fa-clock';
                        statusColor = '#ffc107';
                        statusText = '检索超时';
                    }
                    
                    resultCard.innerHTML = `
                        <div class="card-header">
                            <i class="fas ${statusIcon}" style="color: ${statusColor}"></i>
                            <span>图像检索结果</span>
                            <span style="color: ${statusColor}; margin-left: auto;">${statusText}</span>
                        </div>
                        <div class="card-content">
                            <div class="analysis-item">
                                <h4>图像描述</h4>
                                <p style="white-space: pre-line;">${resultText || '无法生成描述'}</p>
                            </div>
                        </div>
                    `;

                    // 清空之前的结果并添加新结果
                    resultCards.innerHTML = '';
                    resultCards.appendChild(resultCard);

                    // 显示结果区域
                    analysisResult.style.display = 'block';

                    // 如果状态不是FINISHED，显示相应的消息
                    if (result.status === 'FAILED') {
                        alert('图像检索失败: ' + result.result);
                    } else if (result.status === 'TIMEOUT') {
                        alert('图像检索超时，请重试');
                    } else if (result.status === 'FINISHED' && !resultText) {
                        alert('未能获取到有效的检索结果');
                    }

                } catch (error) {
                    console.error('图像检索失败:', error);
                    alert('图像检索失败，请稍后重试\n错误信息：' + error.message);
                } finally {
                    analyzeBtn.disabled = false;
                    analyzeBtn.innerHTML = '<i class="fas fa-brain"></i> 开始检索图像内容';
                }
            };

        } catch (error) {
            console.error('图像检索失败:', error);
            alert('图像检索失败，请稍后重试\n错误信息：' + error.message);
            analyzeBtn.disabled = false;
            analyzeBtn.innerHTML = '<i class="fas fa-brain"></i> 开始检索图像内容';
        }
    });
}); 